/**
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.common.utils;

import com.icinfo.cloud.provider.common.constant.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * 描述:  .<br>
 *
 * @author xiajunwei
 * @date 2019年11月26日
 */
public class RequestUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
    final static String BEARER_TYPE = "Bearer";
    /**
     * 获取access_token
     * @param request
     * @return
     */
    public static String extractAccessToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders("Authorization");
        while (headers.hasMoreElements()) {
            String value = headers.nextElement();
            if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = value.substring(BEARER_TYPE.length()).trim();

                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }

        return null;
    }

    /**
     * 组装成 order 子句
     * @author zhangXiaoYan
     * @date 2020-08-15
     * @param orderField
     * @param orderMethod
     * @return
     */
    public static String transformToOrderBy(String orderField, String orderMethod) {
        String[] orderMethods = new String[]{"asc", "desc"};
        if (!StringUtils.isBlank(orderField) && !StringUtils.isBlank(orderMethod) && orderField.matches(Constant.STRING_ORDERBY_REGEX) && Arrays.asList(orderMethods).contains(orderMethod.toLowerCase())) {
            String ret = "";

            for(int i = 0; i < orderField.length(); ++i) {
                if (orderField.charAt(i) >= 'A' && orderField.charAt(i) <= 'Z') {
                    ret +=  "_" + (char)(orderField.charAt(i) + 32);
                } else {
                    ret = ret + orderField.charAt(i);
                }
            }

            ret = ret + " " + orderMethod.toLowerCase();
            return ret;
        } else {
            LOGGER.info("orderMethod, 排序方法或者传入字段有问题");
            return "";
        }
    }
}
